// 积分充值页面逻辑
const pointsApi = require('../../api/pointsApi');
const app = getApp();

Page({
  data: {
    points: 0,
    packages: [],
    selectedPackage: null,
    loading: false
  },

  onLoad: function (options) {
    // 页面初始化
    this.getPackages();
  },
  
  onShow: function () {
    // 每次显示页面时更新积分
    this.setData({
      points: app.globalData.points || 0
    });
  },
  
  // 获取充值套餐列表
  getPackages: function () {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    pointsApi.getRechargePackages()
      .then(result => {
        const packages = result.packages || [];
        
        this.setData({
          packages,
          selectedPackage: packages.length > 0 ? packages[0] : null
        });
      })
      .catch(err => {
        console.error('获取充值套餐失败', err);
        
        // 使用默认套餐
        const defaultPackages = [
          { id: 1, price: 10, points: 10, discount: '' },
          { id: 2, price: 30, points: 35, discount: '优惠5积分' },
          { id: 3, price: 50, points: 65, discount: '优惠15积分' },
          { id: 4, price: 100, points: 150, discount: '优惠50积分' },
          { id: 5, price: 200, points: 320, discount: '优惠120积分' },
          { id: 6, price: 300, points: 500, discount: '优惠200积分' }
        ];
        
        this.setData({
          packages: defaultPackages,
          selectedPackage: defaultPackages[0]
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },
  
  // 选择套餐
  selectPackage: function (e) {
    const id = e.currentTarget.dataset.id;
    const { packages } = this.data;
    
    const selectedPackage = packages.find(item => item.id === id);
    
    if (selectedPackage) {
      this.setData({ selectedPackage });
    }
  },
  
  // 充值
  recharge: function () {
    if (this.data.loading) return;
    
    const { selectedPackage } = this.data;
    
    if (!selectedPackage) {
      wx.showToast({
        title: '请选择充值套餐',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ loading: true });
    
    // 创建订单
    pointsApi.createRechargeOrder(selectedPackage.id)
      .then(result => {
        const orderId = result.orderId;
        
        // 发起微信支付
        return pointsApi.wxPay(orderId);
      })
      .then(() => {
        // 支付成功，查询最新积分
        return pointsApi.getUserPoints();
      })
      .then(result => {
        // 更新积分
        app.globalData.points = result.points;
        
        this.setData({
          points: result.points
        });
        
        wx.showToast({
          title: '充值成功',
          icon: 'success'
        });
      })
      .catch(err => {
        console.error('充值失败', err);
        
        if (err.errMsg === 'requestPayment:fail cancel') {
          wx.showToast({
            title: '支付已取消',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: '充值失败，请重试',
            icon: 'none'
          });
        }
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  }
}); 